package com.chad.library.adapter.base;

import android.graphics.Rect;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Created by moore on 2018/3/22.
 */

public class OffsetDecoration extends RecyclerView.ItemDecoration {
    private int mStartOffsetPixel, mEndOffsetPixel;

    private boolean mNeedOffset = true;

    public OffsetDecoration(int startOffsetPixel, int endOffsetPixel) {
        mStartOffsetPixel = startOffsetPixel;
        mEndOffsetPixel = endOffsetPixel;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        if (!mNeedOffset){
            return;
        }

        int i = parent.getChildAdapterPosition(view);
        if ((i > 0) && (i < state.getItemCount() - 1)) {
            // Noops
        } else {
            switch (((LinearLayoutManager) parent.getLayoutManager()).getOrientation()) {
                default:
                    return;
                case LinearLayoutManager.HORIZONTAL:
                    if (i == 0) {
                        outRect.left = this.mStartOffsetPixel;
                    }
                    if (i == state.getItemCount() - 1) {
                        outRect.right = this.mEndOffsetPixel;
                    }
                    break;
            }
        }
    }

    public void setNeedOffset(boolean needOffset){
        this.mNeedOffset = true;
    }
}
